# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import atexit
import sys
import os


class InterruptCondition:

    STOPPED = 1

    status: int = None

    def get_status(self):
        return self.status

    def stop(self):
        self.status = self.STOPPED


def get_resource_path(relative_path):
    if getattr(sys, 'frozen', False):
        # 单文件模式下，资源临时解压路径
        base_path = sys._MEIPASS
    else:
        # 开发模式下的路径
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


def driver_init() -> WebDriver:
    # 配置 ChromeDriver 路径，替换为你的 ChromeDriver 路径，你也可以将chromedriver拖入文件根目录，使用'./chromedriver.exe'路径。
    chrome_driver_path = get_resource_path('driver/chromedriver.exe')
    # 初始化 ChromeDriver Service
    service = Service(chrome_driver_path)
    # 打开浏览器时的相关配置，可以根据需求进行打开和关闭
    options = Options()
    options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
    # options.add_argument("--headless=new")  # 使用新版无头模式（Chrome 112+，更接近有头模式）
    # 禁用自动化提示
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument("--window-size=1920,1080")  # 设置窗口尺寸为 1080P
    options.add_argument("--disable-gpu")  # 禁用 GPU 加速（部分环境需要）
    options.add_argument("--start-maximized")  # 启动时最大化窗口
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...")
    # user_data_dir = get_resource_path("../app/application/data")
    # options.add_argument("--user-data-dir=" + user_data_dir)
    # 解决 DevToolsActivePort 问题的核心参数
    options.add_argument("--no-sandbox")  # 禁用沙箱模式（必要时）
    options.add_argument("--disable-dev-shm-usage")  # 避免 /dev/shm 分区不足
    options.add_argument("--remote-debugging-port=9222")  # 强制指定调试端口
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_path = get_resource_path("app/application/GoogleChromePortable/GoogleChromePortable.exe")
    options.binary_location = chrome_path
    options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})  # 开启日志
    web_driver = webdriver.Chrome(service=service, options=options)
    web_driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")  # 防检测
    return web_driver


driver = driver_init()
driver_action = ActionChains(driver)
driver_wait = WebDriverWait(driver, 100)


def get_ele_with_condition(by: str, target: str, condition: InterruptCondition):
    element_present = ec.presence_of_element_located((by, target))
    if condition.get_status() == condition.STOPPED:
        return condition.STOPPED
    return element_present


def wait_until_or_interrupt(by: str, target: str, timeout=100):
    wait = WebDriverWait(driver, timeout)
    wait.until(get_ele_with_condition(by, target))


def cleanup():
    print("浏览器开始退出")
    driver.quit()
    print("浏览器退出成功")


# 注册钩子，在程序终止时执行cleanup()
atexit.register(cleanup)

